/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package app.metatron.discovery.domain.mdm;

import com.google.common.collect.Lists;

import com.querydsl.jpa.JPQLQuery;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.support.QueryDslRepositorySupport;

import java.util.List;

public class MetadataColumnRepositoryImpl extends QueryDslRepositorySupport implements MetadataColumnRepositoryExtends {

  public MetadataColumnRepositoryImpl() {
    super(MetadataColumn.class);
  }

  @Override
  public Page<MetadataColumn> linkedMetadataColumns(String dictionaryId, Pageable pageable) {

    QMetadataColumn qMetadataColumn = QMetadataColumn.metadataColumn;

    JPQLQuery<MetadataColumn> query = from(qMetadataColumn).join(qMetadataColumn.metadata).fetchJoin()
                                                           .where(qMetadataColumn.dictionary.id.eq(dictionaryId));

    Long total = query.fetchCount();

    List<MetadataColumn> contents;
    if(total > pageable.getOffset()) {
      query = getQuerydsl().applyPagination(pageable, query);
      contents = query.fetch();
    } else {
      contents = Lists.newArrayList();
    }

    return new PageImpl<>(contents, pageable, total);
  }
}
